<?php

class LoginController extends BaseController {

	/**
	 * Login form page.
	 *
	 * @access   public
	 * @return   View
	 */
	public function login()
	{
		// Are we logged in?
		//
		if (Auth::check())
		{
			if ($redirect = Session::get('redirect')) {
		        Session::forget('redirect');
		        return Redirect::to($redirect);
    		}
			return Redirect::to('/');
		}

		// Show the page.
		//
		return View::make('login/login');
	}

	/**
	 * Login form processing.
	 *
	 * @access   public
	 * @return   Redirect
	 */
	public function postLogin()
	{
		// Declare the rules for the form validation.
		//
		$rules = array(
			'email'    => 'Required|Email',
			'password' => 'Required'
		);

		// Get all the inputs.
		//
		$email = Input::get('email');
		$password = Input::get('password');

		// Validate the inputs.
		//
		$validator = Validator::make(Input::all(), $rules);

		// Check if the form validates with success.
		//
		if ($validator->passes())
		{
			// Try to log the user in.
			//
			if (Auth::attempt(array('email' => $email, 'password' => $password, 'confirmed' => 1)))
			{
				if ($redirect = Session::get('redirect')) {
			        Session::forget('redirect');
			        return Redirect::to($redirect);
    			}
				return Redirect::to('/')->with('success', 'You have logged in successfully');
			}
			else
			{
				// Redirect to the login page.
				//
				return Redirect::to('login')->with('error', 'Email/password invalid.');
			}
		}

		// Something went wrong.
		//
		return Redirect::to('login')->withErrors($validator->messages());
	}

	/**
	 * Logout page.
	 *
	 * @access   public
	 * @return   Redirect
	 */
	public function logout()
	{
		// Log the user out.
		//
		Auth::logout();

		// Redirect to the users page.
		//
		return Redirect::to('login')->with('success', 'Logged out with success!');
	}
}